<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/t/hplus/include/taglib.jsp"%>

<!DOCTYPE html>
<html>

<head>
    <title>地区管理</title>
	<%@ include file="/WEB-INF/t/hplus/include/head.jsp"%>
	<link href="${ctxStatic}/css/plugins/ztree/zTreeStyle.css" rel="stylesheet">
	<link href="${ctxStatic}/css/plugins/select2/select2.min.css" rel="stylesheet">
	<style type="text/css">
	 /*ztree增加按钮的样式 */
	 .ztree li span.button.add {margin-left:2px; margin-right: -1px; background-position:-144px 0; vertical-align:top; *vertical-align:middle}
	 /*（1）select2在modal里不显示搜索框问题, 第1方案去掉modal上的tabindex="-1", 第2方案修改下面样式的z-index, 
	        （2）出现搜索框但不能聚焦问题，在ready里加$.fn.modal.Constructor.prototype.enforceFocus = function() {};
	        （3）不能聚焦有选中，给select2加个id试试*/ 
	 .select2-dropdown{z-index: 3051 !important;/*99*/}
	</style>
</head>

<body>
    <div class="wrapper wrapper-content">
   	   <div class="row"> 
	    <div class="col-sm-2" style="overflow: hidden"> 
	     <div class="float-e-margins"> 
	      <div class="no-padding"> 
			<ul id="regionTree" data-toggle="regionTree" class="ztree"></ul>
	      </div> 
	     </div> 
	    </div> 
	    <div class="col-sm-10"> 
	     <div class="float-e-margins"> 
	      <div class="no-padding"> 
			<div id="regionToolbar" class="btn-group hidden-xs" role="group"> 
			 <button type="button" class="addRegion btn btn-outline btn-default" title="添加地区"> <i class="glyphicon glyphicon-plus" aria-hidden="true"></i> 添加</button> 
			</div>
			<table id="regionList"></table>
	      </div> 
	     </div> 
	    </div> 
	   </div> 
    </div>
    
<div id="regionModal" class="modal fade" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content animated bounceInUp">
	       <form class="form-horizontal" id="regionForm">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span></button>
				<h4 class="modal-title"></h4>
			</div>
			<div class="modal-body" style="overflow:hidden;">
		        <input type="hidden" id="id" name="id">
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">地区名称：</label> 
		         <div class="col-sm-8"> 
		          <input id="name" name="name" class="form-control" type="text"> 
		         </div> 
		        </div> 
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">地区代码：</label> 
		         <div class="col-sm-8"> 
		          <input id="code" name="code" class="form-control" type="text"> 
		         </div> 
		        </div> 
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">地区类型：</label> 
		         <div class="col-sm-8"> 
		         	<select id="regionType" name="regionType" class="form-control m-b"></select>
		         </div> 
		        </div> 
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">上级地区：</label> 
		         <div class="col-sm-8"> 
                      <select id="parentId" name="parentId" class="js-states form-control" style="width: 100%"></select>
		         </div> 
		        </div> 
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">排序：</label> 
		         <div class="col-sm-8"> 
		          <input id="sort" name="sort" class="form-control" type="text" value="0"> 
		         </div> 
		        </div> 
			</div>
			<div class="modal-footer">
		          <button class="btn btn-primary" type="submit">提交</button> 
		          <button class="btn btn-white" type="submit" data-dismiss="modal">关闭</button>
			</div>
			</form> 
		</div>
	</div>
</div>  

<div class="modal fade" id="delModal" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content animated bounceInUp">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">删除地区</h4>
            </div>
            <div class="modal-body">
                <p>确定删除该地区吗？</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-white" data-dismiss="modal">放弃</button>
                <button type="button" class="btn btn-primary" id="delOk">确定</button>
            </div>
        </div>
    </div>
</div>

<script src="${ctxStatic}/js/plugins/ztree/jquery.ztree.all-3.5.min.js"></script> 
<script src="${ctxStatic}/js/plugins/select2/select2.full.min.js"></script>
<script src="${ctxStatic}/js/plugins/select2/i18n/zh-CN.js"></script>

<script type="text/javascript">
	var $table = $("#regionList"),
		$delModal = $('#delModal'),
		$s2,
		ztreeSetting = {
			view: {
				addHoverDom: addHoverDom,
				removeHoverDom: removeHoverDom,
				selectedMulti: false
			},
			data: {
				simpleData: {
					enable: true
				}
			},
			callback: {
				onClick: onClick
			}
		}
	$(document).ready(function(){
		//解决select2在modal里搜索框不能聚焦问题 
		//$.fn.modal.Constructor.prototype.enforceFocus = function () {}; 
		
		loadRegionTree();
		
		loadRegionList();
		
		$('.addRegion').click(function () {
			showModal("添加地区");
	    });
		
		//提示信息样式
		toastr.options = {
			closeButton: true,
			progressBar: true,
			positionClass: "toast-top-right", //toast-top-center, toast-top-right
			onclick: null,
			timeOut: 2000
		};
		
	});
	
	function onClick(event, treeId, treeNode){
		$table.bootstrapTable('refresh',{url:'${ctx}/region/list', query:{limit:10,offset:0}});
	}
	
	function showRemoveBtn(treeId, treeNode) {
		return false;
	}
	
	function showRenameBtn(treeId, treeNode) {
		return false;
	}
	
	function addHoverDom(treeId, treeNode) {
		var sObj = $("#" + treeNode.tId + "_span");
		if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
		var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
			+ "' title='添加地区' onfocus='this.blur();'></span>";
		sObj.after(addStr);
		var btn = $("#addBtn_"+treeNode.tId);
		if (btn) btn.bind("click", function(){
			//addUser(treeNode.id);
			var treeObj = $.fn.zTree.getZTreeObj("regionTree");
			var node = treeObj.getNodeByTId(treeNode.tId);
			treeObj.selectNode(node);
			showModal("添加地区");
			return false;//阻止冒泡事件
		});
	};
	
	function removeHoverDom(treeId, treeNode) {
		$("#addBtn_"+treeNode.tId).unbind().remove();
	};
	
	function loadRegionTree() {
		$.ajax({
			type : "GET",
			url : '${ctx}/region/ztlist',
			async : false,
			success : function(data) {
				$.fn.zTree.init($("#regionTree"), ztreeSetting, data);
			}
		});
	}
	
	function loadRegionList(){
		$table.bootstrapTable({
			url: "${ctx}/region/list", //get请求, 如果cache为false默认会加随机数, 如果列排序sortable=true则还会加sort和order
			cache: false,
			pagination: true,
	        sidePagination: 'server', // client or server
	        dataField: 'list',
	        pageNumber: 1,
	        pageSize: 10,
	        pageList: [10, 25, 50, 100],
	        selectItemName: 'regionIds',
			showRefresh: true,
			showToggle: true,
			showColumns: true,
	        toolbar: '#regionToolbar',
	        iconSize : "outline",
	        queryParams: 'queryParams',
	        columns:[{
	        	field:'name',
	        	title:'地区名称',
	        	width: 150,
	        	align:'center'
	        },{
	        	field:'code',
	        	title:'地区代码',
	        	align:'center'
	        	//sortable: true,
	        	//sortOrder: "asc"
	        },{
	        	field:'regionType',
	        	title:'地区类型',
	        	align:'center'
	        	//sortable: true,
	        	//sortOrder: "asc"
	        },{
	        	field:'parentId',
	        	title:'上级地区',
	        	width: 150,
	        	align:'center'
	        	//sortable: true,
	        	//sortOrder: "asc"
	        },{
	        	field:'sort',
	        	title:'排序',
	        	align:'center'
	        },{
	        	field:'createTime',
	        	title:'创建时间',
	        	align:'center'
	        },{
	        	field:'action',
	        	title:'操作',
	        	align:'center',
	        	formatter: function(value, row, index){
					var str = '&nbsp;';
					str += '<a href="javascript:void(0)" onclick="editRegion('+ row.id +');" >编辑</a>';
					str += '&nbsp;|&nbsp;';
					str += '<a href="javascript:void(0)" onclick="showDelModal('+ row.id +');" >删除</a>';
					str += '&nbsp;';
					return str;
				}
	        }]
		});
	}
	
	function queryParams(params){
		var node = getSelectNode() || {};
		params.parentId = node.id;
		return params;
	}
	
	function editRegion(id){
		$.ajax({
			type: "GET",
			async: false,
			data: {"id": id, "r": Math.random()},
			dataType: "json",
			url: "${ctx}/region/get",
			success: function(data){
				showModal("编辑地区", data);
			},
			error: function(){
				toastr.error("查询地区失败！");
			}
		});
	}
	
	
	function showDelModal(id){
		$delModal = $('#delModal').modal({
			"backdrop": 'static',
			"show": true
		});
		
		$('#delOk').off();
		$('#delOk').on('click', function(){
			deleteRegion(id);
		});
		
		$delModal.modal('show');
	}
	
	function deleteRegion(id){
		$.ajax({
			type: "POST",
			async: false,
			data: {"id": id},
			dataType: "json",
			url: "${ctx}/region/delete",
			success: function(data){
				if(data.success){
					$delModal.modal("hide");
					afterCRUD();
					toastr.success(data.msg);
				}else{
					$delModal.modal("hide");
					toastr.error(data.msg);
				}
			},
			error: function(){
				$delModal.modal("hide");
				toastr.error("删除地区失败！");
			}
		});
	}
	
	function showModal(title, row) {
		$('#regionModal').off();
		
		var $modal = $('#regionModal').modal({
			"backdrop": 'static', //禁止模态失去焦点关闭
			"show": true
		});
		$modal.find('.modal-title').text(title);
		
		$('#regionModal').on("shown.bs.modal", function(){
			$("#name").focus();
			initRegionType(row);
			initSelect2(row);
		});
		$('#regionModal').on("hidden.bs.modal", function(){
			//重置表单
			$("#regionForm")[0].reset();
			$("#id").val("");
			
			$s2.select2("destroy");
		});

		//表单赋值
		if(row){
			for (var name in row) {
				switch(name){
					case "regionType" :
						//$modal.find('input[name=' + name + ']').val(row[name]);
						$("#regionType").val(row[name]);
						break;
					default:
						$modal.find('input[name=' + name + ']').val(row[name]);
				}
			}
		}
		
		//表单校验及提交
		var e = "<i class='fa fa-times-circle'></i> ";
		$("#regionForm").validate({
			rules : {
				name : {
					required : !0,
					minlength : 1,
					maxlength : 20
				},
				code : {
					required : !0,
					minlength : 1,
					maxlength : 20
				},
				regionType : {
					required : !0,
					minlength : 1,
					maxlength : 20
				},
				sort : {
					required : !0,
					digits: !0,
					minlength : 1,
					maxlength : 5,
				}
			},
			messages : {
				name : {
					required : e + "请输入地区名称",
					minlength : e + "地区名称必须1字符以上",
					maxlength : e + "地区名称最多20个字符"
				},
				code : {
					required : e + "请输入地区代码",
					minlength : e + "地区代码必须1字符以上",
					maxlength : e + "地区代码最多20个字符"
				},
				regionType : {
					required : e + "请输入地区类型"
				},
				sort : {
					required : e + "请输入排序值",
					minlength : e + "排序值必须1个或1个字符以上",
					maxlength : e + "排序值最多5个字符以上"
				}
			},
			submitHandler: function(form){
				$(form).ajaxSubmit({
					type: "POST",
					dataType: "json",
					url: "${ctx}/region/save",
					success: function(data){
						if(data.success){
							$modal.modal("hide");
							afterCRUD();
							toastr.success(data.msg);
						}else{
							toastr.error(data.msg);
						}
					},
					error: function(data){
						toastr.error("保存地区失败！");
					}
				});
			}
		});
	}
	
	function initRegionType(row){
		//取上级地区类型并填充下拉
		$.ajax({
			type: "GET",
			async: false,
			data: {type:"region_type"},
			dataType: "json",
			url: "${ctx}/dict/list",
			success: function(data){
				var options = "";
				$.each(data, function(i,item){
					options = options + "<option value='"+item.id+"'>"+item.label+"</option>";
				});
				$("#regionType").html(options);
			},
			error: function(data){
				toastr.error("查询地区类型失败！");
				$modal.modal("hide");
			}
		});
		if(row){
			$("#regionType").val(row["regionType"]);
		}
	}
	
	function initSelect2(row){
		var node = {"id" : 0, "name" : "请选择上级地区"};
		if(row && row["parentId"] && row["parentId"] != 0){
			node.id = row["parentId"];
			node.name = row["parentName"];
		}else{
			node = getSelectNode() || node;
		}
		$("#parentId").html('<option value="'+node.id+'" selected="selected">'+node.name+'</option>');
		//$s2.val(node.id).trigger("change");
		$s2 = $("#parentId").select2({
			id: "ssssssssss2",
			language: "zh-CN",
			/*placeholder: {
				id: node.id,
				name: node.name
			} ,*/
			//allowClear:true,
			//theme: "bootstrap",
			ajax: {
				type: "GET",
				async: false,
				dataType: "json",
				url: "${ctx}/region/list",
				delay: 500,
				data: function(params){
					params.page = params.page || 1;
					var query = {
						name: params.term, // ? encodeURI(encodeURI(params.term)) : ""
						limit: 10,
						offset: (params.page-1)*10
					}
					return query;
				},
				processResults: function (data, params) {
					params.page = params.page || 1;
			        return {
			        	results: data.list,
			        	pagination: {
			                more: params.page < data.totalPages
			            }
			        };
				},
				cache: false,
				error: function(data){
					toastr.error("查询地区失败！");
					$modal.modal("hide");
				}
			},
			escapeMarkup: function (markup) {
				return markup;   
			},
			minimumInputLength: 1,
			templateResult: function(repo){
				if (repo.loading) return repo.text;
				return repo.name;
				/*if(repo.name){
					var markup = '<div class="clearfix">' +  
					'<div class="col-sm-2">' + repo.id + '</div>' +  
					'<div class="col-sm-8">' + repo.name + '</div>' +  
					'</div>';  
					 return markup;
				}*/
			},  
			templateSelection: function(repo){
				return repo.name || repo.text;
			}
		});
	}
	
	function getSelectNode(){
		var node;
		var zTree = $.fn.zTree.getZTreeObj("regionTree");
		var nodes = zTree.getSelectedNodes();
		if(nodes.length > 0){
			node = nodes[0];
		}
		return node;
	}
	
	function afterCRUD(){
		var node = getSelectNode() || {};
		var selectNodeId = node.id;
		if(selectNodeId){
			var treeObj = $.fn.zTree.getZTreeObj("regionTree");
			var node = treeObj.getNodeByParam("id", selectNodeId);
			loadRegionTree();
			treeObj.selectNode(node);
			//onClick(null, "regionTree", node); //此时使用table的refresh刷新列表，不触发树节点单击事件
			$table.bootstrapTable("refresh");
		}else{
			loadRegionTree();
			$table.bootstrapTable("refresh");
		}
	}
	
</script>

</body>
</html>